<?php
/**
 * Created by PhpStorm.
 * User: wangx08
 * Date: 2015-03-28
 * Time: 17:19
 */
namespace common\repositories\common;

use common\entities\common\MyscrmApplicationEntity;
use common\entities\common\MyscrmContractEntity;
use common\entities\common\MyscrmOrganizationForTestEntity;
use common\entities\common\MyscrmOrganizationToAuthorizeEntity;
use common\entities\common\PigcmsWxUserEntity;
use common\entities\ConfigEntity;
use common\entities\KfsDbEntity;
use common\entities\myhtsq\MyscrmDeliveryChangeLogEntity;
use common\repositories\BaseRepository;
use common\entities\common\MyscrmOrganizationEntity;
use common\support\QRSupport;
use yii\db\Query;
use yii\helpers\ArrayHelper;
use common\support\PageParam;
use common\support\Helper;
use yii\helpers\StringHelper;

use linslin\yii2\curl;
use Yii;

class MyscrmOrganizationRepository extends BaseRepository
{

    /**
     * 根据租户UniqueName(企业号)获取其ID
     * @param $orgName
     * @return string
     */
    public function getOrgId($orgName)
    {
        $org = $this->getOrgByUniqueName($orgName);
        if ($org) {
            return $org->Id;
        }
        return null;
    }

    public function getAppInfoByToken($token)
    {
        $user = PigcmsWxUserEntity::findOne(
            ["token" => $token]
        );
        return $user;
    }

    public function getConnection($orgName)
    {
        $org = MyscrmOrganizationEntity::findOne([
            "UniqueName" => $orgName
        ]);
        return $this->__splitOrgConnectionString($org);
    }

    /**
     * 根据租户企业ID获取详情
     * @param $orgId
     * @return null|MyscrmOrganizationEntity
     */
    public function getOrgById($orgId)
    {
        return MyscrmOrganizationEntity::findOne([
            "Id" => $orgId
        ]);
    }
    /**
     * 根据关键词获取租户列表
     * @param $orgId
     * @return array
     */
    public function getAllOrgs($fields)
    {
        if(!empty($fields)) {
            return MyscrmOrganizationEntity::find()->select($fields)->all();
        }else{
            return MyscrmOrganizationEntity::findAll([]);
        }
    }
    /**
     * 拆分租户的数据库连接字符串
     * @param $org
     * @return array|null
     */
    private function __splitOrgConnectionString($org)
    {
        if (is_null($org))
            return null;

        return $this->getConnectionByConnStr($org->ConnectionString);
    }

    public function getConnectionByConnStr($connectionString)
    {
        $arr = explode(';', $connectionString);
        $result = [];
        foreach ($arr as $key => $item) {
            $parts = explode("=", $item);
            if (count($parts) > 1) {
                $result[$parts[0]] = $parts[1];
            }
        }
        return $result;
    }

    /**
     * 根据租户UniqueName(企业号)获取详情
     * @param $orgName
     * @return null|MyscrmOrganizationEntity
     */
    public function getOrgByUniqueName($orgName)
    {
        return MyscrmOrganizationEntity::findOne([
            "UniqueName" => $orgName
        ]);
    }

    /**
     * 根据租户FriendlyName(企业名称)获取详情
     * @param $friendlyName
     * @return null|MyscrmOrganizationEntity
     */
    public function getOrgByFriendlyName($friendlyName)
    {
        return MyscrmOrganizationEntity::findOne([
            "FriendlyName" => $friendlyName
        ]);
    }

    public function getAllTestOrg()
    {
        return MyscrmOrganizationForTestEntity::find()
            ->asArray()
            ->all();
    }

    /**
     * 分页获取租户列表
     * @param PageParam $pageParam
     * @param string $keyword 搜索关键字
     * @param int $isBq 是否过滤百强租户
     * @param int $isTest 是否测试租户
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getOrganizationListByPage(PageParam $pageParam, $keyword, $isBq, $isTest)
    {
        if (is_null($keyword) && empty($keyword)) {
            return [];
        }

        $query = MyscrmOrganizationEntity::find()
            ->select('Id, DatabaseName, InstanceName, InstanceId, UniqueName, FriendlyName, State, Email, UpgradeSerialNumber,
                        IsCanUpgrade, CreatedOn, ModifiedOn, VersionNumber, CustomManager, CustomManagerPhone, CustomManagerEmail, Deliver, DeliverPhone, DeliverEmail, ScheduleKey,
                        Area, LogoUrl, CustomManagerGUID, DeliverGUID, isBq ')
            ->leftJoin('myscrm_organization_for_test t', 't.orgcode=myscrm_organization.UniqueName')
            ->filterWhere([
                'or',
                ['like', 'FriendlyName', $keyword],
                ['like', 'UniqueName', $keyword],
            ]);

        if ($isBq) {
            $query->andWhere(['isBq' => 1]);
        }

        if ($isTest == '1') {
            $query->andWhere('t.orgcode is not null');
        }elseif($isTest == '0'){
            $query->andWhere('t.orgcode is null');
        }

        $total = $query->count();
        $items = $query->orderBy('CreatedOn desc')
            ->offset($pageParam->getSkipByPageParam())
            ->limit($pageParam->pageSize)
            ->asArray()
            ->all();

        return Helper::setPageResult($total, $items);
    }

    /**
     * 根据ID获取租户信息对象
     * @param $organizationId
     * @return null|MyscrmOrganizationEntity
     */
    public static function getById($organizationId)
    {
        return MyscrmOrganizationEntity::findOne([
            'Id' => $organizationId
        ]);
    }

    /**
     * 根据ID删除记录
     * @param $organizationId
     * @return int
     */
    public function deleteById($organizationId)
    {
        return MyscrmOrganizationEntity::deleteAll([
            'Id' => $organizationId
        ]);
    }

    /**
     * 删除租户授权信息
     * @param $organizationId
     * @return int
     */
    public function deleteOrganizationToAuthorizeByOrganizationId($organizationId)
    {
        return MyscrmOrganizationToAuthorizeEntity::deleteAll([
            'OrganizationId' => $organizationId
        ]);
    }

    public function updateStatesByOrganizationId($organizationId, $state)
    {
        $entity = MyscrmOrganizationEntity::find()
            ->where(['Id' => $organizationId])
            ->one();

        if ($entity) {
            $entity->State = intval($state);
            $entity->save();
            return true;
        }
        return false;
    }

    /**
     * 更新租户email
     * @param $email
     * @param MyscrmOrganizationEntity $organizationEntity
     * @return bool
     */
    public function updateEmailOrganizationId($email, $organizationEntity)
    {
        $organizationEntity->Email = $email;
        if ($organizationEntity->save()) {
            return true;
        }
        return false;
    }

    /**
     * 更新租户交付信息
     * @param $info
     * @return bool
     * @throws \Exception
     */
    public function updateOrganizationDeliverInfo($info)
    {
        $org = $this->getOrgByUniqueName($info['orgname']);
        $orgOld = clone $org;
        if (empty($org)) {
            throw new \Exception("租户不存在");
        }
        $org['Area'] = ArrayHelper::getValue($info, 'area', '');
        $org['Deliver'] = ArrayHelper::getValue($info, 'deliver', '');
        $org['DeliverPhone'] = ArrayHelper::getValue($info, 'deliver_phone', '');
        $org['DeliverEmail'] = ArrayHelper::getValue($info, 'deliver_email', '');
        $org['DeliverGUID'] = ArrayHelper::getValue($info, 'deliver_guid', '');
        $org['CustomManager'] = ArrayHelper::getValue($info, 'custom_manager', '');
        $org['CustomManagerPhone'] = ArrayHelper::getValue($info, 'custom_manager_phone', '');
        $org['CustomManagerEmail'] = ArrayHelper::getValue($info, 'custom_manager_email', '');
        $org['CustomManagerGUID'] = ArrayHelper::getValue($info, 'custom_manager_guid', '');
        if ($org->save()) {
            try {
                //保存成功，则记录原来的信息
                $logEntity = new MyscrmDeliveryChangeLogEntity();
                $logEntity->isNewRecord = true;
                $logEntity->logId = \common\support\StringHelper::uuid();
                $logEntity->OrganizationId = $orgOld['Id'];
                $logEntity->CustomManager = $orgOld['CustomManager'];
                $logEntity->CustomManagerPhone = $orgOld['CustomManagerPhone'];
                $logEntity->CustomManagerGUID = $orgOld['CustomManagerGUID'];
                $logEntity->CustomManagerEmail = $orgOld['CustomManagerEmail'];
                $logEntity->Deliver = $orgOld['Deliver'];
                $logEntity->DeliverPhone = $orgOld['DeliverPhone'];
                $logEntity->DeliverEmail = $orgOld['DeliverEmail'];
                $logEntity->DeliverGUID = $orgOld['DeliverGUID'];
                $logEntity->CreatedOn = date('Y-m-d H:i:s');
                $logEntity->CreatedBy = \Yii::$app->user->identity->userguid;
                $logEntity->save();
            } catch (\Exception $e) {
                \Yii::error((string)$e);
            }
            return true;
        } else {
            throw $this->throwException($org->getFirstErrors());
        }
    }


    /**
     * 获取租户列表（select2控件）
     * @param string $keyword 搜索关键字
     * @param int $limit
     * @return array
     */
    public function getOrganizationListForSelect2($keyword, $limit = 10)
    {
        if (is_null($keyword) && empty($keyword)) {
            return [];
        }

        return MyscrmOrganizationEntity::find()
            ->select('Id as id,FriendlyName as text')
            ->where(['like', 'FriendlyName', $keyword])
            ->orWhere(['like', 'UniqueName', $keyword])
            ->orderBy(['FriendlyName' => SORT_ASC])
            ->limit($limit)
            ->asArray()
            ->all();
    }

    public function addTestOrganization($orgCode, $desc = '')
    {
        $orgEntity = new MyscrmOrganizationForTestEntity();

        $orgEntity->isNewRecord = true;
        $orgEntity->orgcode = $orgCode;
        $orgEntity->desc = $desc;

        try {
            $orgEntity->save();
        } catch (\Exception $e) {
            \Yii::error('添加测试租户失败：' . $e->getMessage());
            return self::setAndReturn(__LINE__, '添加测试租户失败' . $e->getMessage());
        }

        return true;
    }

    public function deleteTestOrganization($orgCode)
    {
        try {
            MyscrmOrganizationForTestEntity::deleteAll(['orgcode' => $orgCode]);
        } catch (\Exception $e) {
            \Yii::error('删除测试租户失败：' . $e->getMessage());
            return self::setAndReturn(__LINE__, '删除测试租户失败' . $e->getMessage());
        }

        return true;
    }

    /**
     * 新增租户
     * @param $organizationArr
     * @param $newConnection
     * @param $passwordMD5
     * @return bool
     */
    public function createOrganization($organizationArr, $newConnection, $passwordMD5)
    {
        //插入myscrm_organization表
        $sqlOrganization = sprintf("
INSERT  INTO myscrm_organization ( ConnectionString, FriendlyName, Id, State, UniqueName, DatabaseName, InstanceName, InstanceId, Email, UpgradeSerialNumber, VersionNumber, ScheduleKey, CreatedOn, ModifiedOn)
VALUES ('%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s','%s',%s,%s)",
            $organizationArr['ConnectionString'], $organizationArr['FriendlyName'], $organizationArr['Id'], 1, $organizationArr['UniqueName'], $organizationArr['DatabaseName'], $organizationArr['InstanceName'], $organizationArr['InstanceId'], $organizationArr['Email'], $organizationArr['UpgradeSerialNumber'], $organizationArr['VersionNumber'], $organizationArr['ScheduleKey'], 'NOW()', 'NOW()');

        $organizationResult = $this->executeSqlConfig($sqlOrganization);
        if ($organizationResult === false) {
            \Yii::error('RDS数据库创建后无法往租户表插入信息，报错SQL：' . $sqlOrganization);
            return false;
        }

        //插入pigcms_users表
        $sqlPigCms = "insert into pigcms_users (OrganizationId, gid, username, password, email, createtime, lasttime, status, createip, lastip, diynum, activitynum, card_num, card_create_status, money, viptime,
            wechat_card_num, serviceUserNum, db_host, db_name, db_port, db_user, db_pwd ) values(
            '" . $organizationArr['Id'] . "', 4, '" . $organizationArr['UniqueName'] . "', '" . $passwordMD5 . "','', '', '' , 1, '', '', 0, 0, 0, 0, 0, '', 0, 0, '" . $newConnection['server'] . "', '" . $newConnection['database'] . "', '" . $newConnection['port'] . "', '" . $newConnection['uid'] . "', '" . $newConnection['pwd'] . "' )";
        $pigCmsResult = $this->executeSqlConfig($sqlPigCms);
        if ($pigCmsResult === false) {
            \Yii::error('RDS数据库创建后无法往小猪用户表插入信息，报错SQL：' . $sqlPigCms);
            return false;
        }

        return true;
    }

    /**
     * 默认启用拓客中心新模式、项目级客户确认模式
     * @param $orgId
     * @return bool
     */
    public function insertFunctionUpgrade($orgId)
    {
        $sql = "INSERT INTO myscrm_functionupgrade (
	          `functionUpgradeId`,
	          `organizationId`,
	          `functionName`,
	          `functionMode`
          )
          SELECT uuid(), '" . $orgId . "', fu.`functionName`, fu.`functionMode`
          FROM `myscrm_functionupgrade` fu
          INNER JOIN `myscrm_organization` o ON fu.`organizationId` = o.`Id`
          WHERE o.`UniqueName` = 'empty'; ";

        $functionUpgradeResult = $this->executeSqlConfig($sql);
        if ($functionUpgradeResult === false) {
            \Yii::error('默认启用拓客中心新模式、项目级客户确认模式失败');
            return false;
        }

        return true;
    }

    /**
     * 租户库执行SQL
     * @param string $sql
     * @return bool
     */
    public function executeSql($sql)
    {
        if ($sql) {
            return KfsDbEntity::getDb()->createCommand($sql)->execute();
        }
        return false;
    }

    /**
     * 配置库执行SQL
     * @param string $sql
     * @return bool
     */
    public function executeSqlConfig($sql)
    {
        if ($sql) {
            return ConfigEntity::getDb()->createCommand($sql)->execute();
        }
        return false;
    }

    public function getAllOrganizationCodes()
    {
        $allOrgs = MyscrmOrganizationEntity::find()->where(['State' => 1])->asArray()->all();

        $orgCodes = [];
        foreach ($allOrgs as $key => $org) {
            $orgCodes[] = $org['UniqueName'];
        }
        return $orgCodes;
    }

    /**
     * 项目授权概况列表
     * @param $userEntity
     * @param $isAreaOwner
     * @param $areaId
     * @param $disable
     * @param $orgState
     * @param $keyword
     * @param $chooseAll
     * @return mixed
     */
    public function getOrgProjectAuthList($userEntity, $isAreaOwner, $areaId, $disable, $orgState, $keyword, $chooseAll = false)
    {
        $query = $this->getOrgProjectAuthListQuery(true, $userEntity, $isAreaOwner, $areaId, $disable, $orgState, $keyword, $chooseAll);
        //如果是搜索 则还需要加上未在本区域的合同相关信息
        if (!empty($keyword) && $chooseAll) {
            $query2 = $this->getOrgProjectAuthListQuery(false, $userEntity, $isAreaOwner, $areaId, $disable, $orgState, $keyword, $chooseAll);
            $query->union($query2);
        }
        return $query->asArray()->all();
    }


    /**
     * 获取查询的query
     * @param bool $inArea 是否获取在区域内的
     * @param $userEntity
     * @param $isAreaOwner
     * @param $areaId
     * @param $disable
     * @param $orgState
     * @param $keyword
     * @param bool $chooseAll
     * @return static
     */
    private function getOrgProjectAuthListQuery($inArea = true, $userEntity, $isAreaOwner, $areaId, $disable, $orgState, $keyword, $chooseAll = false)
    {
        $today = date("Y-m-d");
        $month3 = date('Y-m-d', strtotime('+3 month'));

        $query = MyscrmContractEntity::find()
            ->select('myscrm_contract.OrganizationId, myscrm_contract.ContractId')
            ->leftJoin('myscrm_organization', 'myscrm_contract.OrganizationId=myscrm_organization.Id');
        $query->andFilterWhere(['not', ['myscrm_organization.IsCanUpgrade' => 0]]);//过滤非正式环境中不再维护的租户


        if ($inArea) {
            $query->andFilterWhere(['myscrm_contract.AreaId' => $areaId]);
        } else {
            $query->andWhere(
                ['or',
                    ['not', ['myscrm_contract.AreaId' => $areaId]],
                    ['myscrm_contract.AreaId' => null]
                ]);
        }
        $phone = $userEntity->MobilePhone;
        if (strlen($userEntity->MobilePhone) > 11) {
            $phone = substr($userEntity->MobilePhone, -11);//取最后11位字符
        }
        if ($inArea) {
            //不是区域负责人，也不是指定的领导，只能看交付顾问或者客户经理是自己的数据
            if (!$isAreaOwner && !in_array($userEntity->UserGUID, \Yii::$app->params['allAuthUserId'])) {
                $query->andWhere(['or',
                        ['myscrm_contract.DeliverPhone' => $phone],
                        ['myscrm_contract.CustomManagerPhone' => $phone]
                    ]
                );
            }
            //合同当事人希望能够看到自己的数据,不论区域
            if (empty($keyword) && $chooseAll) {
                $query->orFilterWhere(['or',
                        ['myscrm_contract.DeliverPhone' => $phone],
                        ['myscrm_contract.CustomManagerPhone' => $phone]
                    ]
                );
            }
        } else {
            $query->andWhere(['or',
                    ['myscrm_contract.DeliverPhone' => $phone],
                    ['myscrm_contract.CustomManagerPhone' => $phone]
                ]
            );
        }

        //->andWhere(['myscrm_organization.State' => 1])//过滤已禁用租户
        $query->andFilterWhere(['myscrm_organization.State' => $disable])
            ->andFilterWhere(
                ['or',
                    ['like', 'myscrm_organization.UniqueName', $keyword],
                    ['like', 'myscrm_organization.FriendlyName', $keyword],
                    ['like', 'myscrm_contract.CustomManager', $keyword],
                    ['like', 'myscrm_contract.Deliver', $keyword],
                    ['like', 'myscrm_contract.DeliverPhone', $keyword],
                    ['like', 'myscrm_contract.CustomManagerPhone', $keyword],
                    ['like', 'myscrm_contract.ContractNum', $keyword]
                ]
            );
        switch ($orgState) {
            case 'normal'://正常，3个月后才到期
                $query->andWhere(['>', 'EndOn', $month3]);
                break;
            case 'will_expire'://即将到期
                $query->andWhere(['and', ['>', 'EndOn', $today], ['<=', 'EndOn', $month3]]);
                break;
            case 'expire':
                //已到期
                $query->andWhere(['<', 'EndOn', $today]);
                break;
        }
        return $query;
    }

    /**
     * @param $organizationIds
     * @param $pageIndex
     * @param $pageSize
     * @param bool $isPage 是否分页
     * @return array|\yii\db\ActiveRecord[]
     */
    public function getListByIds($organizationIds, $isPage = true, $pageIndex = 1, $pageSize = 10)
    {
        $query = MyscrmOrganizationEntity::find()
            ->select('Id, UniqueName, FriendlyName, State, CreatedOn , AliasName')
            ->where(['Id' => $organizationIds])
            ->orderBy('CreatedOn asc')
            ->asArray();
        if ($isPage) {
            $query->offset(($pageIndex - 1) * $pageSize)->limit($pageSize);
        }
        return $query->all();
    }

    /**
     * 指定租户指定合同的所有应用授权概况
     * @param $organizationId
     * @param $contractIds
     * @return mixed
     */
    public function getAuthCountGroupByApplicationCode($organizationId, $contractIds, $appCode)
    {
        $query = MyscrmApplicationEntity::find()
            ->select('SUM(myscrm_organizationtoauthorize.TotalNum) as totalNum')
            ->leftJoin('myscrm_organizationtoauthorize', 'myscrm_application.ApplicationId=myscrm_organizationtoauthorize.ApplicationId')
            ->where(['myscrm_organizationtoauthorize.OrganizationId' => $organizationId, 'myscrm_organizationtoauthorize.ContractId' => $contractIds, 'myscrm_application.UniqueName' => $appCode])->scalar();

        return $query;
    }

    public function getAllAuthCount()
    {
        return MyscrmApplicationEntity::find()
            ->select('myscrm_organizationtoauthorize.OrganizationId, myscrm_organizationtoauthorize.ContractId, myscrm_application.UniqueName, SUM(myscrm_organizationtoauthorize.TotalNum) as totalNum, myscrm_application.ApplicationId')
            ->leftJoin('myscrm_organizationtoauthorize', 'myscrm_application.ApplicationId=myscrm_organizationtoauthorize.ApplicationId')
            ->groupBy('myscrm_organizationtoauthorize.OrganizationId, myscrm_organizationtoauthorize.ContractId, myscrm_application.UniqueName')->indexBy(function ($row) {
                return implode('_', [$row['OrganizationId'], $row['ContractId'], $row['UniqueName']]);
            })->asArray()->all();
    }

    /**
     * 通过租户ID、合同ID获取合同
     * @param $organizationId
     * @param $contractIds
     * @return mixed
     */
    public function getContractByOrganizationId($organizationId, $contractIds)
    {
        $query = MyscrmContractEntity::find()
            ->select('ContractId,ContractNum, PartyA, BeginOn, EndOn, AreaId,CustomManager,CustomManagerEmail,CustomManagerPhone,Deliver,DeliverEmail,DeliverPhone')
            ->where(['OrganizationId' => $organizationId, 'ContractId' => $contractIds])
            ->asArray()
            ->all();
        return $query;

    }

    /**
     * 获取交付信息变更记录
     * @param $orgId
     * @return null|MyscrmDeliveryChangeLogEntity
     */
    public function getDeliveryChangeLog($orgId)
    {
        $query = MyscrmDeliveryChangeLogEntity::find()
            ->select('myscrm_delivery_change_log.*, myscrm_erp_user.UserName')
            ->leftJoin('myscrm_erp_user', 'myscrm_erp_user.UserGUID=myscrm_delivery_change_log.CreatedBy')
            ->where(['OrganizationId' => $orgId])
            ->orderBy('CreatedOn desc')
            ->asArray()
            ->all();
        return $query;
    }

    public function setBq($orgId)
    {
        return MyscrmOrganizationEntity::updateAll([
            'isBq' => 1,
        ], [
            'Id' => $orgId,
        ]);
    }

    public function unsetBq($orgId)
    {
        return MyscrmOrganizationEntity::updateAll([
            'isBq' => 0,
        ], [
            'Id' => $orgId,
        ]);
    }

    public static function addRechargeLog($orgCode, $count, $amount)
    {
        $curl = new curl\Curl();

        $appCfg = ArrayHelper::getValue(Yii::$app->params, "QmyxRefactorInterface", null);
        if (empty($appCfg)) {
            throw new \Exception("找不到获取已授权数的远程接口配置");
        }
        $appsecret = $appCfg['appSecret'];
        $nowtimestamp = time();
        $sign = md5($nowtimestamp . "#" . $appsecret);
        $siteUrl = rtrim($appCfg['url'], '/') . '?r=yun-market/add-recharge-log';
        $param = [
            'appid' => $appCfg["appId"],
            't' => $nowtimestamp,
            'sign' => $sign,
            'orgcode' => $orgCode,
            'count' => $count,
            'amount' => $amount,
        ];
        $curl->setOption(CURLOPT_POSTFIELDS, http_build_query($param));
        $res = self::curlPost($curl, $siteUrl);
        Yii::error(json_encode($param));
        if ($res['retCode'] == 0) {
            return $res['data'];
        }

        return false;
    }

    /**
     * @param $curl curl\Curl
     * @param $url
     * @return mixed
     * @throws \Exception
     */
    private static function curlPost($curl, $url)
    {
        $res = $curl->post($url, true);
        if($res === false){
            throw new \Exception('调用extapi(' . $url . ')出错:' . $curl->response);
        }
        return json_decode($res,true);
    }
    public function getOrgsListByKeyword($keyword,$page=1,$pageSize=20,$fields='',$returnTatalCount=true)
    {
        if (empty($keyword)) {
            return [];
        }
        if(!$page||intval($page)<1){
            $page=1;
        }
        if(!$pageSize||intval($pageSize)<1){
            $pageSize=20;
        }
        $query = MyscrmOrganizationEntity::find();
        if(!empty($fields)) {
            $query=$query->select($fields);
        }
        $query=$query->filterWhere([
            'or',
            ['like', 'FriendlyName', $keyword],
            ['like', 'UniqueName', $keyword],
        ]);
        $list = $query->offset(($page-1)*$pageSize)->limit($pageSize)->all();
        if($returnTatalCount) {
            $total = $query->count();
        }else{
            $total = count($list);
        }
        return ['total'=>$total,'list'=>$list];
    }
    public function getOrgsListByCodes($orgCodes,$fields='')
    {
        if (empty($orgCodes)) {
            return [];
        }
        $query = MyscrmOrganizationEntity::find();
        if(!empty($fields)) {
            $query=$query->select($fields);
        }
        return $query->Where(['in', 'UniqueName', $orgCodes])->all();
    }
}